// Copyright (C) 2012 by Johann Duscher <jonny.dee@gmx.net>
//
// This file is part of barcodeart-pp.
//
// barcodeart-pp is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// barcodeart-pp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with barcodeart-pp. If not, see <http://www.gnu.org/licenses/>.

#include <cassert>
#include <sstream>

#include <png++/png.hpp>

#include <barcodeart/IBarCode.hpp>

#include "barcodeart/pngwriter/PNGWriter.hpp"
#include "barcodeart/pngwriter/PNGWriterConfig.hpp"


namespace barcodeart
{

namespace pngwriter
{

int PNGWriter::write(std::ostream& out, const IBarCode& barCode, const IWriterConfig& iConfig) const
{
    const PNGWriterConfig& config = dynamic_cast<const PNGWriterConfig&>(iConfig);

    png::image< png::gray_pixel_1 > image(barCode.getWidth(), barCode.getHeight());

    for (int y = 0; y < barCode.getHeight(); ++y)
        for (int x = 0; x < barCode.getWidth(); ++x)
            image.set_pixel(x, y, png::gray_pixel_1(barCode.isBlack(y, x) ? 0 : 1));

    // Passing 'out' directly to image.write_stream(...) method causes a segmentation fault.
    // I don't know why, but passing a std::stringstream seems to work...?
    std::stringstream strOut;
    image.write_stream(strOut);
    strOut.flush();
    out << strOut.str();
    out.flush();

    return 0;
}

}

}
